<template>
  <el-container>
    <el-header>
      <h1>XX系统登录界面</h1>
    </el-header>

    <el-main>
      <div id="login-wrap">  
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-main>

    <el-footer>

    </el-footer>
  </el-container>
</template>

<style scoped>
  #login-wrap {
    margin: 80px auto;
    width: 400px;
  }

  .el-input {
    margin-bottom: 10px;
  }
</style>

<script>
// 引入登录接口
import { userLogin } from "../request/api"

  export default {
    data() {
      var checkUsername = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }
        setTimeout(() => {
          if (!/^[a-zA-Z][a-zA-Z0-9]+$/.test(value)) {
            callback(new Error('请输入正确的用户名'));
          } else {
            if (value.length > 8) {
              callback(new Error('用户名太长'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
      var validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPassword !== '') {
            this.$refs.ruleForm.validateField('checkPassword');
          }
          callback();
        }
      };
      return {
        ruleForm: {
          password: '',
          username: ''
        },
        rules: {
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          username: [
            { validator: checkUsername, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            userLogin(this.ruleForm).then((res) => {
              if (res.data.code == 200) {
                this.$message.success(res.data.msg);
                sessionStorage.setItem('userInfo', JSON.stringify(res.data.list))
                //验证成功跳转到index界面
                this.$router.push("/index");
              } else {
                this.$message.error(res.data.msg);
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>